import { AfterViewChecked, Component, ElementRef, EventEmitter, Injector, Output, ViewChild } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { map as _map, filter as _filter } from 'lodash-es';
import { finalize } from 'rxjs/operators';
import { Table } from 'primeng/table';
import { Paginator } from 'primeng/paginator';
import { LazyLoadEvent } from 'primeng/api';
import { AppModalComponentBase } from '@shared/common/app-modal-component-base';
import { IEntityDtoOfGuid, PagedFlowNodeDto, SetStatusInput, WorkFlowDesignServiceProxy, WorkFlowQueryServiceProxy } from '@shared/service-proxies/service-proxies';
import { FlowNodeDetailModalComponent } from './flow-node-detail-modal.component';

export class PagedFlowNodeDtoExt extends PagedFlowNodeDto{
    nextNames:string
    backNames:string
}

@Component({
    selector: 'flow-node-modal',
    templateUrl: './flow-node-modal.component.html'
})
export class FlowNodeModalComponent extends AppModalComponentBase {

    @ViewChild('flowNodeModal', { static: true }) modal: ModalDirective;
    @ViewChild('dataTable', { static: true }) dataTable: Table;
    @ViewChild('paginator', { static: true }) paginator: Paginator;

    @ViewChild('flowNodeDetailModal',{static: true}) flowNodeDetailModal:FlowNodeDetailModalComponent;

    selectedDatas: IEntityDtoOfGuid[];
    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();
    workFlowId:string
    constructor(
        injector: Injector,
        private _workFlowDesignServiceProxy:WorkFlowDesignServiceProxy
    ) {
        super(injector);
    }

    show(id:string): void {
        this.modalExpandOb.resetStates();
        this.modal.show();
        this.workFlowId = id;
        this.getListData()
    }

    getListData(event?: LazyLoadEvent) {
        this.selectedDatas = [];
        if (this.primengTableHelper.shouldResetPaging(event)) {
            if (this.primengTableHelper.TryChangePage(this.paginator, 0)) {
                return;
            }
        }
        this.primengTableHelper.showLoadingIndicator();
        this._workFlowDesignServiceProxy.getPagedFlowNode(this.workFlowId).pipe(finalize(() => this.primengTableHelper.hideLoadingIndicator())).subscribe(res=>{
            this.primengTableHelper.totalRecordsCount = res.length;
            let pagedFlowNodeDtoExts:PagedFlowNodeDtoExt[] = [];
            for (const value of res) {
                let item = new PagedFlowNodeDtoExt();
                Object.assign(item,value);
                item.nextNames = this.getNodeNamesByIdList(value.nextNodeList,res);
                item.backNames = this.getNodeNamesByIdList(value.backNodeList, res);
                pagedFlowNodeDtoExts.push(item)
            }
            this.primengTableHelper.records = pagedFlowNodeDtoExts;
            this.primengTableHelper.hideLoadingIndicator();
        });
    }
   

    close(): void {
        this.modal.hide();
    }

    create(){
        this.flowNodeDetailModal.show(this.workFlowId,'');
    }

    edit(record:PagedFlowNodeDtoExt){
        this.flowNodeDetailModal.show(this.workFlowId,record.id);
    }

    changeState(state:boolean):void {
        let ids = this.selectedDatas.map(item=>item.id);
        if (ids.length == 0) return;
        let setStatusInput = new SetStatusInput();
        setStatusInput.idList = ids;
        setStatusInput.isActive = state;
        this._workFlowDesignServiceProxy.setFlowNodeStatus(setStatusInput).subscribe(res=>{
            this.notify.success(this.l('Success'));
            this.getListData();
        });
    }

    delete(){
        let ids = this.selectedDatas.map(item=>item.id);
        if (ids.length == 0) return;
        this.message.confirm(this.l('DeleteWarningMessage'), this.l('AreYouSure'),
        (isConfirmed) => {
            if (!isConfirmed) return;
            this._workFlowDesignServiceProxy.deleteFlowNode(ids).subscribe(res=>{
                this.getListData();
                this.notify.success(this.l('SuccessfullyDeleted'))
            });
        })
       
    }

    goBackToList(e){
        if (e){
            this.getListData();
        }
    }

    private getNodeNamesByIdList(idList:string, data:PagedFlowNodeDto[]):string {
        let arr:string[] = [], i:number, j:number, tempId:string, item:PagedFlowNodeDto;
        if (idList) {
            var splitIds = idList.split(',');
            for (i = 0; i < splitIds.length; i++) {
                tempId = splitIds[i];
                for (j = 0; j < data.length; j++) {
                    item = data[j];
                    if (tempId === item.id) {
                        arr.push(item.name);
                    }
                }
            }
        }
        return arr.join(',');
    }

    
}
